package com.general.message.notice.utils;

import com.general.common.func.VoidFunc;
import com.general.common.utils.StringUtils;
import com.general.message.notice.entity.NoticeInfo;
import com.general.message.notice.enums.NoticeType;
import com.general.message.notice.service.INoticeInfoService;
import com.general.message.push.websocket.WsSupport;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Slf4j
@Component
public class NoticeUtils {

    private static NoticeUtils noticeUtils;

    @Autowired
    private INoticeInfoService noticeInfoService;

    @PostConstruct
    public void init() {
        noticeUtils = this;
        noticeUtils.noticeInfoService = this.noticeInfoService;
    }
    /**
     * 消息通知-
     */
    public static void pushNoticeTo(NoticeType noticeType,String userId){

        if (noticeType == null) {
            log.error("通知属性为空，请检查完善通知内容！");
            return;
        }
        if (StringUtils.isBlank(userId)) {
            log.error("通知人为空！");
            return;
        }
        NoticeInfo noticeInfo = new NoticeInfo();

        noticeInfo.setTitle(noticeType.getTitle());
        noticeInfo.setContent(noticeType.getContent());
        noticeInfo.setType(noticeType.getType());
        noticeInfo.setMenuKey(noticeType.getMenuKey());
        noticeInfo.setReceiveUser(userId);
        noticeUtils.noticeInfoService.save(noticeInfo);

        //提醒前台页面刷新消息提醒
        WsSupport.sendMessageToAll("refresh");
    }


    public static void pushNoticeTo(NoticeType noticeType, String userId, VoidFunc func) {
        if (noticeType == null) {
            log.error("通知属性为空，请检查完善通知内容！");
            return;
        }
        if (StringUtils.isBlank(userId)) {
            log.error("通知人为空！");
            return;
        }
        NoticeInfo noticeInfo = new NoticeInfo();

        noticeInfo.setTitle(noticeType.getTitle());
        noticeInfo.setContent(noticeType.getContent());
        noticeInfo.setType(noticeType.getType());
        noticeInfo.setMenuKey(noticeType.getMenuKey());
        noticeInfo.setReceiveUser(userId);
        noticeUtils.noticeInfoService.save(noticeInfo);

        //提醒前台页面刷新消息提醒
        func.call();
    }

}
